from flask import Blueprint, jsonify, request
from smart_attendance_system.database.db_connection import execute_query
from datetime import datetime, timedelta
import json

admin_bp = Blueprint('admin', __name__)

# 仪表盘数据接口
@admin_bp.route('/api/dashboard/stats', methods=['GET'])
def get_dashboard_stats():
    try:
        # 获取今日日期
        today = datetime.now().date()
        
        # 获取今日出勤人数
        today_attendance_query = """
            SELECT COUNT(DISTINCT employee_id) as count 
            FROM attendance_records 
            WHERE DATE(check_in_time) = %s
        """
        today_attendance = execute_query(today_attendance_query, (today,))
        today_attendance = today_attendance[0]['count'] if today_attendance else 0
        
        # 获取待审批请假数
        pending_leaves_query = """
            SELECT COUNT(*) as count 
            FROM leave_requests 
            WHERE status = 'pending'
        """
        pending_leaves = execute_query(pending_leaves_query)
        pending_leaves = pending_leaves[0]['count'] if pending_leaves else 0
        
        # 获取总员工数
        total_employees_query = "SELECT COUNT(*) as count FROM employees"
        total_employees = execute_query(total_employees_query)
        total_employees = total_employees[0]['count'] if total_employees else 0
        
        return jsonify({
            'today_attendance': today_attendance,
            'pending_leaves': pending_leaves,
            'total_employees': total_employees
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 员工管理接口
@admin_bp.route('/api/employees', methods=['GET'])
def get_employees():
    try:
        # 获取所有员工信息，添加排序以便展示
        query = """
            SELECT 
                employee_id, name, department, position, 
                CASE WHEN face_encoding IS NOT NULL THEN 1 ELSE 0 END as face_registered, 
                created_at, updated_at
            FROM employees
            ORDER BY created_at DESC
        """
        employees = execute_query(query)
        
        # 记录返回的员工数量
        print(f"获取到 {len(employees)} 名员工的信息")
        
        # 如果没有获取到员工信息，返回空列表而不是错误
        if not employees:
            print("未找到任何员工信息")
            return jsonify([])
            
        # 调整日期格式为前端可处理的格式
        for employee in employees:
            if 'created_at' in employee and employee['created_at']:
                employee['created_at'] = employee['created_at'].isoformat()
            if 'updated_at' in employee and employee['updated_at']:
                employee['updated_at'] = employee['updated_at'].isoformat()
        
        return jsonify(employees)
    except Exception as e:
        error_msg = f"获取员工信息失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

@admin_bp.route('/api/employees', methods=['POST'])
def add_employee():
    try:
        data = request.json
        # 获取必要的字段
        employee_id = data.get('employee_id')
        name = data.get('name')
        
        if not employee_id or not name:
            return jsonify({'error': '员工ID和姓名为必填项'}), 400
            
        # 检查员工ID是否已存在
        check_query = "SELECT employee_id FROM employees WHERE employee_id = %s"
        existing_employee = execute_query(check_query, (employee_id,))
        
        if existing_employee:
            return jsonify({'error': f'员工ID {employee_id} 已存在'}), 409
        
        # 从前端获取的其他字段
        department = data.get('department', '')
        position = data.get('position', '')
        
        # face_registered字段由系统根据face_encoding自动管理，不接受前端输入
        # 新增员工时，face_registered默认为0，face_encoding为NULL
        
        query = """
            INSERT INTO employees (employee_id, name, department, position, face_registered)
            VALUES (%s, %s, %s, %s, 0)
        """
        params = (employee_id, name, department, position)
        execute_query(query, params, fetch=False)
        
        return jsonify({
            'message': f'员工 {name} (ID: {employee_id}) 添加成功',
            'employee_id': employee_id
        })
        
    except Exception as e:
        error_msg = f"添加员工失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

@admin_bp.route('/api/employees/<employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    try:
        print(f"尝试删除员工: {employee_id}")
        
        # 首先检查员工是否存在
        check_query = "SELECT employee_id, name FROM employees WHERE employee_id = %s"
        employee = execute_query(check_query, (employee_id,))
        
        if not employee:
            error_msg = f"员工不存在: {employee_id}"
            print(error_msg)
            return jsonify({'error': error_msg}), 404
        
        # 获取员工名称用于日志记录
        employee_name = employee[0]['name'] if employee and 'name' in employee[0] else "未知"
        print(f"找到员工: {employee_id} ({employee_name}), 将进行删除操作")
            
        # 删除员工 - 先处理外键关联
        try:
            # 禁用外键检查来处理级联删除
            disable_fk = "SET FOREIGN_KEY_CHECKS = 0"
            execute_query(disable_fk, fetch=False)
            
            # 删除员工相关的所有请假记录
            delete_leave_query = "DELETE FROM leave_requests WHERE employee_id = %s"
            leave_result = execute_query(delete_leave_query, (employee_id,), fetch=False)
            print(f"已删除员工 {employee_id} 的请假记录")
            
            # 删除员工相关的所有考勤记录
            delete_attendance_query = "DELETE FROM attendance_records WHERE employee_id = %s"
            attendance_result = execute_query(delete_attendance_query, (employee_id,), fetch=False)
            print(f"已删除员工 {employee_id} 的考勤记录")
            
            # 删除员工本身
            delete_employee_query = "DELETE FROM employees WHERE employee_id = %s"
            employee_result = execute_query(delete_employee_query, (employee_id,), fetch=False)
            print(f"已删除员工: {employee_id} ({employee_name})")
            
            # 重新启用外键检查
            enable_fk = "SET FOREIGN_KEY_CHECKS = 1"
            execute_query(enable_fk, fetch=False)
            
            return jsonify({'message': f'员工 {employee_name} (ID: {employee_id}) 删除成功'})
        except Exception as e:
            # 确保重新启用外键检查
            try:
                enable_fk = "SET FOREIGN_KEY_CHECKS = 1"
                execute_query(enable_fk, fetch=False)
            except:
                pass
            
            error_msg = f"删除员工 {employee_id} 时出错: {str(e)}"
            print(error_msg)
            return jsonify({'error': error_msg}), 500
    except Exception as e:
        error_msg = f"删除员工 {employee_id} 请求处理失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

@admin_bp.route('/api/employees/<employee_id>', methods=['GET'])
def get_employee(employee_id):
    try:
        # 查询员工信息
        query = """
            SELECT employee_id, name, department, position, face_registered,
                   created_at, updated_at, 
                   CASE WHEN face_encoding IS NOT NULL THEN 1 ELSE 0 END as has_face_data
            FROM employees 
            WHERE employee_id = %s
        """
        employee = execute_query(query, (employee_id,))
        
        if not employee:
            return jsonify({'error': f'员工ID {employee_id} 不存在'}), 404
        
        # 处理日期格式
        if 'created_at' in employee[0] and employee[0]['created_at']:
            employee[0]['created_at'] = employee[0]['created_at'].isoformat()
        if 'updated_at' in employee[0] and employee[0]['updated_at']:
            employee[0]['updated_at'] = employee[0]['updated_at'].isoformat()
            
        return jsonify(employee[0])
        
    except Exception as e:
        error_msg = f"获取员工信息失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

@admin_bp.route('/api/employees/<employee_id>', methods=['PUT'])
def update_employee(employee_id):
    try:
        data = request.json
        
        # 首先检查员工是否存在
        check_query = """
            SELECT employee_id, name, face_encoding 
            FROM employees 
            WHERE employee_id = %s
        """
        employee = execute_query(check_query, (employee_id,))
        
        if not employee:
            return jsonify({'error': f'员工ID {employee_id} 不存在'}), 404
            
        # 获取前端传来的数据
        name = data.get('name')
        department = data.get('department', '')
        position = data.get('position', '')
        
        # 从数据库获取face_encoding状态，决定face_registered的值
        has_face_encoding = employee[0].get('face_encoding') is not None
        
        # 更新员工信息，face_registered根据face_encoding自动设置
        query = """
            UPDATE employees 
            SET name = %s, 
                department = %s, 
                position = %s,
                face_registered = %s,
                updated_at = NOW()
            WHERE employee_id = %s
        """
        params = (name, department, position, 1 if has_face_encoding else 0, employee_id)
        execute_query(query, params, fetch=False)
        
        return jsonify({
            'message': f'员工 {name} (ID: {employee_id}) 更新成功',
            'employee_id': employee_id,
            'face_registered': 1 if has_face_encoding else 0
        })
        
    except Exception as e:
        error_msg = f"更新员工信息失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

# 同步人脸注册状态
@admin_bp.route('/api/employees/sync-face-status', methods=['POST'])
def sync_face_registration_status():
    try:
        # 自动同步所有员工的face_registered状态
        query = """
            UPDATE employees 
            SET face_registered = CASE WHEN face_encoding IS NOT NULL THEN 1 ELSE 0 END,
                updated_at = NOW()
        """
        execute_query(query, fetch=False)
        
        # 获取同步后的状态统计
        stats_query = """
            SELECT 
                SUM(CASE WHEN face_registered = 1 THEN 1 ELSE 0 END) as registered,
                SUM(CASE WHEN face_registered = 0 THEN 1 ELSE 0 END) as not_registered,
                COUNT(*) as total
            FROM employees
        """
        stats = execute_query(stats_query)
        
        return jsonify({
            'message': '所有员工的人脸注册状态已同步',
            'stats': stats[0] if stats else {}
        })
        
    except Exception as e:
        error_msg = f"同步人脸注册状态失败: {str(e)}"
        print(error_msg)
        return jsonify({'error': error_msg}), 500

# 考勤记录管理接口
@admin_bp.route('/api/attendance', methods=['GET'])
def get_attendance_records():
    try:
        date_from = request.args.get('date_from')
        date_to = request.args.get('date_to')
        
        if not date_from or not date_to:
            today = datetime.now().date()
            date_from = today.strftime('%Y-%m-%d')
            date_to = today.strftime('%Y-%m-%d')
        
        query = """
            SELECT a.*, e.name 
            FROM attendance_records a 
            JOIN employees e ON a.employee_id = e.employee_id 
            WHERE DATE(a.check_in_time) >= %s 
            AND DATE(a.check_in_time) <= %s
        """
        records = execute_query(query, (date_from, date_to))
        return jsonify(records)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 请假管理接口
@admin_bp.route('/api/leave-requests', methods=['GET'])
def get_leave_requests():
    try:
        status = request.args.get('status', 'all')
        
        query = """
            SELECT l.*, e.name 
            FROM leave_requests l 
            JOIN employees e ON l.employee_id = e.employee_id
        """
        if status != 'all':
            query += " WHERE l.status = %s"
            records = execute_query(query, (status,))
        else:
            records = execute_query(query)
            
        return jsonify(records)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@admin_bp.route('/api/leave-requests/<request_id>', methods=['PUT'])
def update_leave_request(request_id):
    try:
        data = request.json
        query = """
            UPDATE leave_requests 
            SET status = %s, admin_comment = %s 
            WHERE id = %s
        """
        params = (
            data['status'],
            data.get('admin_comment', ''),
            request_id
        )
        execute_query(query, params, fetch=False)
        return jsonify({'message': '请假申请状态更新成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 制度管理接口
@admin_bp.route('/api/policies', methods=['GET'])
def get_policies():
    try:
        query = "SELECT * FROM policies"
        policies = execute_query(query)
        
        # 处理日期格式
        for policy in policies:
            if 'created_at' in policy and policy['created_at']:
                if not isinstance(policy['created_at'], datetime):
                    try:
                        # 尝试转换为datetime对象
                        policy['created_at'] = datetime.fromisoformat(str(policy['created_at']).replace('Z', '+00:00'))
                    except (ValueError, TypeError):
                        # 如果转换失败，设置为None
                        policy['created_at'] = None
            else:
                policy['created_at'] = None
                
        return jsonify(policies)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@admin_bp.route('/api/policies', methods=['POST'])
def add_policy():
    try:
        data = request.json
        query = """
            INSERT INTO policies (title, category, content) 
            VALUES (%s, %s, %s)
        """
        params = (
            data['title'],
            data['category'],
            data['content']
        )
        execute_query(query, params, fetch=False)
        return jsonify({'message': '制度添加成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@admin_bp.route('/api/policies/<policy_id>', methods=['DELETE'])
def delete_policy(policy_id):
    try:
        query = "DELETE FROM policies WHERE id = %s"
        execute_query(query, (policy_id,), fetch=False)
        return jsonify({'message': '制度删除成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500 